package com.kelvem.saas.workbanch.ontology.address.handle;

import com.kelvem.saas.workbanch.fsm.anno.handle.RegisterHandle;
import com.kelvem.saas.workbanch.fsm.entity.Entity;
import com.kelvem.saas.workbanch.fsm.core.EventContext;
import com.kelvem.saas.workbanch.fsm.handle.Handle;
import com.kelvem.saas.workbanch.ontology.address.model.AddressEntity;
import com.kelvem.saas.workbanch.ontology.order.model.OrdersEntity;
import com.kelvem.saas.workbanch.ontology.risk.BlacklistEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author kelvem
 */
@Service
@Slf4j
public class AddressSignHandle extends Handle {
    
    @Override
    @RegisterHandle(entityClass={OrdersEntity.class, BlacklistEntity.class})
    public void execute() {
    
        List<AddressEntity> addressList = Entity.instance().selectList(AddressEntity.class);
        
        log.info("Handle[" + getName() + "] addressList=" + addressList);
        
        if (addressList == null) {
            return;
        }
    
        for (AddressEntity address :
                addressList) {
            completeSign(address);
        }
    
        EventContext.print();
    }
    
    private void completeSign(AddressEntity address) {
        StringBuilder key = new StringBuilder();
        
        key.append(format(address.getProvince()));
        key.append(format(address.getCity()));
        key.append(format(address.getCounty()));
        key.append(format(address.getAddressDetail()));
        key.append(format(address.getName()));
        key.append(format(address.getTel()));
        
        log.info("AddressSignHandle.completeSign, key=" + key);
        
        String sign = DigestUtils.sha1Hex(key.toString());
        log.info("AddressSignHandle.completeSign, sign=" + sign);
        
        address.setSign(sign);
    }
    
    private String format(String str) {
        if (str == null) {
            return "";
        }
        return str.replaceAll(" ", "").replaceAll(",", "").replaceAll("，", "");
    }
}
